class LinksController < ApplicationController
  before_action :set_link, only: [:show, :edit, :update, :destroy]

  def index
    @links = Link.all
  end


  def new
    @link = Link.new
  end


  def show
  end

 
  def create
    begin
      origin = link_params[:origin]
      custom = link_params[:custom]

      link =  Link.find_by origin: origin
      if (link) then
        @link = link
      else 
        @link = Link.new
        @link.origin = origin
        if custom and Link.find_by custom: custom
        elsif custom
          @link.short = custom
        else 
          @link.short = random_hex
        end
        if !@link.save
          render 'new'
          return
        end
      end
      redirect_to @link
    rescue => e
      render 'new'
    end
  end



  def go
    link = Link.find_by short: params[:short]
    if link 
      redirect_to link.origin
    else
      redirect_to root_path
    end
  end




  private
    # Use callbacks to share common setup or constraints between actions.
    def set_link
      @link = Link.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def link_params
      params.require(:link).permit(:origin, :custom)
    end


    def random_hex
      short = SecureRandom.hex 3
      while Link.find_by short: short
        short = SecureRandom.hex 3
      end
      short
    end


end
